package com.Iconcat.system.service.impl;

import com.Iconcat.system.entity.CatPrize;
import com.Iconcat.system.entity.DrawRecord;
import com.Iconcat.system.entity.RechargeRecord;
import com.Iconcat.system.mapper.CatPrizeMapper;
import com.Iconcat.system.mapper.CatUserMapper;
import com.Iconcat.system.mapper.DrawRecordMapper;
import com.Iconcat.system.response.Result;
import com.Iconcat.system.service.CatUserService;
import com.Iconcat.system.service.DrawRecordService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zzq
 * @since 2023-11-13
 */
@Service
public class DrawRecordServiceImpl extends ServiceImpl<DrawRecordMapper, DrawRecord> implements DrawRecordService {

    @Resource
    private DrawRecordMapper drawRecordMapper;
    @Resource
    private CatPrizeMapper catPrizeMapper;
    @Resource
    private CatUserMapper catUserMapper;

    @Override
    public Result drawPrize(Integer userId, String prizeName, Integer drawType) {
        // 获取用户抽奖次数
        Integer  drawRecord  = catUserMapper.selectDrawCountByUserId(userId);
//        int drawCount = drawRecord.getC
        // 判断用户是否有抽奖次数
        if (drawRecord > 0) {
            // 计算概率
            List<CatPrize> prizes = catPrizeMapper.selectPrizeList();
            // 计算总权重
            int totalWeight = prizes.stream().mapToInt(CatPrize::getWeight).sum();

            // 根据权重计算概率
            double randomValue = Math.random();
            double cumulativeProbability = 0;

            CatPrize drawnPrize = null;

            for (CatPrize prize : prizes) {
                double probability = (double) prize.getWeight() / totalWeight;
                cumulativeProbability += probability;

                if (randomValue <= cumulativeProbability) {
                    // 抽中了该奖品
                    // 更新用户抽奖次数，每次抽奖减一
                    int affectedRows = catUserMapper.updateDrawCountByUserId(userId);

                    if (affectedRows > 0) {
                        // 更新成功
                    } else {
                        // 更新失败
                    }
                    System.out.println(prize);
                    drawnPrize = prize;
                    break;
                }
            }

            if (drawnPrize != null) {
                // 添加抽奖记录
                DrawRecord drawRecord1= new DrawRecord();
                drawRecord1.setUserid(userId);
                drawRecord1.setDrawTime(new Date());
                drawRecord1.setPrizeId(drawnPrize.getPrizeId());
                drawRecord1.setDrawType(drawType);
                drawRecord1.setDrawNumber(generateDrawNumber()); // Use your method to generate draw number

                // 插入数据库
                int insertResult = drawRecordMapper.insert(drawRecord1);
                // 返回抽奖成功，将奖品信息放入Map中
                if (insertResult > 0) {
                    Map<String, Object> resultData = new HashMap<>();
                    resultData.put("prizeName", drawnPrize.getPrizeName());
                    resultData.put("prizeType", drawnPrize.getPrizeType());
//                resultData.put("prizeValue", drawnPrize.getPrizeValue());

                    return Result.ok().data(resultData).message("抽奖成功");
                    //抽奖成功后点击到数据库
                }else{
                    // 插入抽奖记录失败
                    return Result.error().message("抽奖记录添加失败");
                }

            } else {
                // 返回抽奖成功
                return Result.ok().message("抽奖成功");
            }
        } else {
            // 返回抽奖失败，没有抽奖次数
            return Result.error().message("今日抽奖次数用完");
        }
    }

    @Override
    public Result recordList(Integer userId, Integer current, Integer size) {
        // 计算 offset
        int offset = (current - 1) * size;

        List<DrawRecord> drawRecordList = drawRecordMapper.selectDrawRecordWithPrize(userId, offset, size);
       // 查询抽奖总数
        int total = drawRecordMapper.selectTotalDrawRecordCount(userId);;
        Map<String, Object> result = new HashMap<>();
        result.put("drawRecord", drawRecordList);
        result.put("total",total);

        return Result.ok().data(result);
    }

    @Override
    public IPage<Map<String, Object>> getDrawRecordListPage(Page<DrawRecord> page) {
        return drawRecordMapper.getDrawRecordListPage(page);
    }


    // 生成抽奖单号的方法
    private String generateDrawNumber() {
        // 获取当前时间
        Date now = new Date();
        // 格式化时间为字符串，可以根据需要调整格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String dateString = dateFormat.format(now);

        // 拼接抽奖单号前缀，这里假设是"CJ"
        String drawNumberPrefix = "CJ";

        // 生成唯一标识，这里简化为取当前时间的毫秒数
        long uniqueIdentifier = System.currentTimeMillis();

        // 拼接抽奖单号
        return drawNumberPrefix + dateString + uniqueIdentifier;

    }
//    public static void main(String[] args) {
//        DrawRecordServiceImpl D=new DrawRecordServiceImpl();
//        String generateDrawNumber=D.generateDrawNumber();
//        System.out.println(generateDrawNumber);
//    }



}
